package article_api

import (
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/ctype"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/es_ser"
	"time"
)

type ArticleUpdateRequest struct {
	Title    string   `json:"title"`     //文章标题
	Abstract string   `json:"abstract"`  //文章简介
	Content  string   `json:"content"`   //文章内容
	Category string   `json:"category"`  //文章分类
	Source   string   `json:"source"`    //文章来源
	Link     string   `json:"link"`      //原文链接
	BannerID uint     `json:"banner_id"` //文章封面id
	Tags     []string `json:"tags"`      //文章标签
	ID       string   `json:"id"`
}

// ArticleUpdate 更新文章接口
// @Summary 更新文章
// @Description 更新指定ID的文章信息
// @Tags 文章管理
// @Accept json
// @Produce json
// @Param article body ArticleUpdateRequest true "文章信息"
// @Security ApiKeyAuth
// @Success 200 {object} res.Response{}
// @Failure 400 {object} res.Response "参数错误"
// @Failure 401 {object} res.Response "未授权访问"
// @Failure 404 {object} res.Response "文章不存在"
// @Failure 500 {object} res.Response "内部服务器错误"
// @Router /api/articles [post]
func (ArticleApi) ArticleUpdate(c *gin.Context) {
	var cr ArticleUpdateRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailedWithError(err, &cr, c)
		return
	}
	var bannerUrl string
	if cr.BannerID != 0 {
		err = global.DB.Model(models.BannerModel{}).Where("id=?", cr.BannerID).Select("path").Scan(&bannerUrl).Error
		if err != nil {
			res.FailedWithMsg("banner不存在", c)
			return
		}
	}
	article := models.ArticleModel{
		UpdatedAt: time.Now().Format("2006-01-02 15:04:05"),
		Title:     cr.Title,
		Keyword:   cr.Title,
		Abstract:  cr.Abstract,
		Content:   cr.Content,
		Category:  cr.Category,
		Source:    cr.Source,
		Link:      cr.Link,
		BannerID:  cr.BannerID,
		BannerUrl: bannerUrl,
		Tags:      cr.Tags,
	}

	maps := structs.Map(&article)
	var DataMap = map[string]any{}
	//去掉空值
	for key, v := range maps {
		switch val := v.(type) {
		case string:
			if val == "" {
				continue
			}
		case uint:
			if val == 0 {
				continue
			}
		case int:
			if val == 0 {
				continue
			}
		case ctype.Array:
			if len(val) == 0 {
				continue
			}
		case []string:
			if len(val) == 0 {
				continue
			}
		}
		DataMap[key] = v
	}
	//通过id判断文章是否存在
	err = article.GetDataByID(cr.ID)
	if err != nil {
		global.Log.Error(err)
		res.FailedWithMsg("文章不存在", c)
		return
	}
	err = es_ser.ArticleUpdateCommon(cr.ID, DataMap)
	if err != nil {
		global.Log.Error(err)
		res.FailedWithMsg("文章更新失败", c)
		return
	}
	//更新成功,同步到全文搜索
	newArticle, _ := es_ser.CommonDetail(cr.ID)
	if article.Content != newArticle.Content || article.Title != newArticle.Title {
		es_ser.DeleteFullTextByID(cr.ID)
		es_ser.AsyncArticleByFullText(cr.ID, article.Title, newArticle.Content)
	}
	res.OkWithMsg("更新成功", c)
}
